package com.team.RunsFast_Api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team.RunsFast_Api.config.RedisKeyConfig;
import com.team.RunsFast_Api.dao.StoreDao;
import com.team.RunsFast_Api.dto.PositionDto;
import com.team.RunsFast_Api.dto.StoreAddDto;
import com.team.RunsFast_Api.dto.StoreNearDto;
import com.team.RunsFast_Api.dto.StoreQueryDto;
import com.team.RunsFast_Api.service.intf.StoreService;
import com.team.RunsFast_Api.util.JedisUtil;
import com.team.runsfast.entity.Store;
import com.team.runsfast.vo.PageVo;
import com.team.runsfast.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;

import java.sql.Array;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

import static com.team.RunsFast_Api.util.JedisUtil.*;

/**
 * @author fxy
 * @date 2022/9/24
 */
@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreDao storeDao;
    //添加一条店铺信息,根据用户的定位信息
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public R addStore(StoreAddDto store, String lats,String lngs) {
        //在数据库中添加一条商铺信息 String title, String adress, String info, String phone, Double post
        storeDao.insert(new Store(store.getTitle(),store.getAdress(),store.getInfo(),store.getPhone(),store.getPost()));
        //在redis中添加一条商铺的经纬度坐标信息
        Double lat = Double.parseDouble(lats);
        Double lng = Double.parseDouble(lngs);
        //将当前的商铺添加入redis中，值为 系统值+店铺名称
//        if(JedisUtil.getGeo())
        JedisUtil.addGeo(RedisKeyConfig.STORE_POS,lng,lat,store.getTitle());
        return R.ok();
    }


    //查询用户当前位置的店铺
    @Override                   //lat是维度  lng是经度
    @Transactional(rollbackFor = SQLException.class)
    public R selectByUserPos(String lats,String lngs,String token) {
        //将当前的用户坐标添加到redis中
        if(getPos(RedisKeyConfig.STORE_POS,token)==null){
            //将用户坐标加入到redis中
            addGeo(RedisKeyConfig.STORE_POS,Double.parseDouble(lngs),Double.parseDouble(lats),token);
        }
        List<GeoRadiusResponse> radius = getRadius(RedisKeyConfig.STORE_POS, Double.parseDouble(lngs), Double.parseDouble(lats), 10, GeoUnit.KM);
        List<StoreNearDto> nearDtoList = new ArrayList<>();
        for(GeoRadiusResponse r:radius){
               //如果数据中存储的市  app:store:position-店铺名称
               String title = r.getMemberByString();
               //去数据库里面查询店铺的信息
               Store store = storeDao.selectOne(new QueryWrapper<Store>().eq("title", title));
               //在redis中计算两者直接的距离
               Double dist = getDist(RedisKeyConfig.STORE_POS, token, r.getMemberByString());
               //添加到list中
               //Long id, Integer flag, String title, String imgurl, String adress, String info, Double comments, String phone, Double post, Double distance
               if(Objects.nonNull(store)){
                   nearDtoList.add(new StoreNearDto(store.getId(),store.getFlag(),title,store.getImgurl(),store.getAdress(),store.getInfo(),store.getComments(),store.getPhone(),store.getPost(),dist));
               }
        }
        return R.ok(nearDtoList);
    }

    //查询用户类型
    @Override
    public R selectByType(String token, StoreQueryDto storeQueryDto) {
        QueryWrapper<Store> wrapper = new QueryWrapper<>();
        int flag = 1;
        if(storeQueryDto.getField()=="comments") {
            //按评分排序
            wrapper.orderByDesc("comments");
        }
        wrapper.like("info",storeQueryDto.getTitle());
        Page<Store> page=storeDao.selectPage(new Page<>(storeQueryDto.getPage(),storeQueryDto.getSize()),wrapper);

        List<StoreNearDto> listNear = new ArrayList<>();

        for(Store store : page.getRecords()){
            //查询数据库中的字段
            Double dist = getDist(RedisKeyConfig.STORE_POS, store.getTitle(), token);
            listNear.add(new StoreNearDto(store.getId(),store.getFlag(),storeQueryDto.getTitle(),store.getImgurl(),store.getAdress(),store.getInfo(),store.getComments(),store.getPhone(),store.getPost(),dist));
        }
        if(flag != 1){
            listNear.stream().sorted(Comparator.comparingDouble(StoreNearDto::getDistance).reversed()).collect(Collectors.toList());
        }
        return R.ok(new PageVo<>(page.getTotal(),page.getPages(),listNear));
    }

    @Override
    public R selectByComments(String lats, String lngs,String token) {
        //返回
        List<StoreNearDto> data = (List<StoreNearDto>) selectByUserPos(lats, lngs, token).getData();
        return R.ok(data.stream().limit(5).collect(Collectors.toList()));

    }

    //查询指定店铺
    @Override
    public R selectById(Long id) {
        return R.ok(storeDao.selectOne(new QueryWrapper<Store>().eq("id",id)));
    }
}
